package cn.wwcyc.config;

import cn.hutool.core.util.StrUtil;
import cn.wwcyc.domain.User;
import cn.wwcyc.exception.WWException;
import cn.wwcyc.exception.WWExceptionEnum;
import cn.wwcyc.service.UserService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration
public class JWTInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;
    private static final Logger log = LoggerFactory.getLogger(JWTInterceptor.class);
    public JWTInterceptor(){
        System.out.println("JWTInterceptor()");

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        if(StrUtil.isBlank(token)){
            throw new WWException(WWExceptionEnum.AUTHORITION_FAIL);
        }
        // 获取 token 中的 用户信息
        String userId = null;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new WWException(WWExceptionEnum.USER_NOT_EXISTED);
        }
        Date expiresAt = JWT.decode(token).getExpiresAt();
        if(expiresAt.before(new Date())){
            throw new WWException(WWExceptionEnum.AUTHORITION_EXPIRE);
        }
//        Integer id = 7;
        User user = userService.getById(userId);
        if(user == null) {
            throw new WWException(WWExceptionEnum.USER_NOT_EXISTED);
        }


        // 利用用户密码，解密验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
//            System.out.println("=== token验证失败 ===");
//            httpServletResponse.sendError(401);
            throw new WWException(WWExceptionEnum.AUTHORITION_FAIL);
        }
        return true;
    }
}
